package com.snack.shop.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 微信数据解密工具类
 * 用于解密微信小程序返回的加密数据（如手机号、用户信息等）
 */
@Slf4j
public class WxDecryptUtil {

    private static final String ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * 解密微信加密数据
     * @param encryptedData 加密数据（Base64编码）
     * @param sessionKey sessionKey（Base64编码）
     * @param iv 初始向量（Base64编码）
     * @return 解密后的JSON字符串
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv) {
        try {
            // Base64解码
            byte[] encryptedBytes = Base64.decodeBase64(encryptedData);
            byte[] sessionKeyBytes = Base64.decodeBase64(sessionKey);
            byte[] ivBytes = Base64.decodeBase64(iv);

            // 创建密钥
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, 0, sessionKeyBytes.length, ALGORITHM);
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

            // 创建Cipher对象
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            // 解密
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            String decryptedStr = new String(decryptedBytes, StandardCharsets.UTF_8);

            log.debug("微信数据解密成功");
            return decryptedStr;
        } catch (Exception e) {
            log.error("微信数据解密失败", e);
            throw new RuntimeException("解密失败：" + e.getMessage());
        }
    }
}
